package com.innovation.ic.cyz.base.service.cyz.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.FileUtil;
import com.innovation.ic.cyz.base.mapper.cyz.RepairOrderFileMapper;
import com.innovation.ic.cyz.base.model.cyz.RepairOrderFile;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.constant.repairOrderFiles.RepairOrderFilesConstant;
import com.innovation.ic.cyz.base.pojo.variable.cyz.rabbit_mq.FilesPojo;
import com.innovation.ic.cyz.base.service.cyz.RepairOrderFileService;
import com.innovation.ic.cyz.base.value.config.FtpAccountConfig;
import com.jcraft.jsch.ChannelSftp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 工单附件接口具体实现类
 */
@Service
@Transactional
public class RepairOrderFileServiceImpl extends ServiceImpl<RepairOrderFileMapper, RepairOrderFile> implements RepairOrderFileService {
    private static final Logger log = LoggerFactory.getLogger(RepairOrderFileServiceImpl.class);

    @Resource
    private RepairOrderFileMapper repairOrderFileMapper;

    @Resource
    private FtpAccountConfig ftpAccountConfig;

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 通过文件地址删除工单附件
     *
     * @param filePath 文件地址
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> deleteByFilePath(String filePath) {
        try {
            // 删除附件数据
            deleteFtpFile(filePath);
        } catch (Exception e) {
            log.error("通过文件地址删除工单附件出现问题,原因:", e);
        }
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        return serviceResult;
    }

    /**
     * 根据流程记录id查询附件地址集合
     *
     * @param id 流程记录id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<FilesPojo>> selectFilesByRecordId(Long id) {
        List<FilesPojo> result = repairOrderFileMapper.selectFilesByRecordId(id);

        ServiceResult<List<FilesPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 删除工单附件
     *
     * @param id 工单附件id
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delete(Long id) {
        RepairOrderFile repairOrderFile = repairOrderFileMapper.selectById(id);

        int i = repairOrderFileMapper.deleteById(id);
        if (i > 0) {
            log.info("删除工单附件成功,删除数据的id为[{}]", id);

            // 删除附件数据
            deleteFtpFile(repairOrderFile.getFilePath());
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.DELETE_SUCCESS);
        return serviceResult;
    }

    /**
     * 删除ftp文件
     *
     * @param filePath 文件路径
     */
    private void deleteFtpFile(String filePath) {
        if (!Strings.isNullOrEmpty(filePath)) {
            try {
                String imageUrlBasePath = ftpAccountConfig.getImageUrlBasePath();
                if (!Strings.isNullOrEmpty(filePath)) {
                    // 图片
                    if (filePath.contains(imageUrlBasePath)) {
                        String[] split = filePath.split(imageUrlBasePath);
                        if (split.length == 2) {
                            String imgPath = ftpAccountConfig.getImageSaveBasePath() + "/" + split[1];
                            JSONObject fileInfo = getFilePathNameByFilePath(imgPath);
                            if (!fileInfo.isEmpty()) {
                                String path = (String) fileInfo.get(RepairOrderFilesConstant.PATH);
                                String fileName = (String) fileInfo.get(RepairOrderFilesConstant.FILE_NAME);
                                log.info("图片删除路径为:[{}]", path);
                                log.info("图片名称为:[{}]", fileName);
                                serviceHelper.getSftpChannelManager().delete(path, fileName);
                            }
                        }
                    }

                    // 视频
                    String videoUrlBasePath = ftpAccountConfig.getVideoUrlBasePath();
                    if (filePath.contains(videoUrlBasePath)) {
                        String[] split = filePath.split(videoUrlBasePath);
                        if (split.length == 2) {
                            String videoPath = ftpAccountConfig.getVideoSaveBasePath() + "/" + split[1];
                            JSONObject fileInfo = getFilePathNameByFilePath(videoPath);
                            if (!fileInfo.isEmpty()) {
                                String path = (String) fileInfo.get(RepairOrderFilesConstant.PATH);
                                String fileName = (String) fileInfo.get(RepairOrderFilesConstant.FILE_NAME);
                                log.info("视频删除路径为:[{}]", path);
                                log.info("视频名称为:[{}]", fileName);
                                serviceHelper.getSftpChannelManager().delete(path, fileName);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("文件下载出现问题,原因:", e);
            }
        }
    }

    /**
     * 工单附件下载
     *
     * @param id 工单附件id
     * @return 返回附件内容
     */
    @Override
    public ServiceResult<Boolean> download(Long id, HttpServletResponse response) throws IOException {
        RepairOrderFile repairOrderFile = repairOrderFileMapper.selectById(id);
        if (repairOrderFile != null && !Strings.isNullOrEmpty(repairOrderFile.getFilePath())) {
            String filePath = repairOrderFile.getFilePath();

            try {
                String imageUrlBasePath = ftpAccountConfig.getImageUrlBasePath();
                String fileName = repairOrderFile.getFileName();
                if (!Strings.isNullOrEmpty(filePath)) {
                    // 图片
                    if (filePath.contains(imageUrlBasePath)) {
                        String[] split = filePath.split(imageUrlBasePath);
                        if (split.length == 2) {
                            String imgPath = ftpAccountConfig.getImageSaveBasePath() + "/" + split[1];
                            log.info("图片下载地址为:[{}]", imgPath);
                            byte[] bytes = FileUtil.getBytesByFile(imgPath);
                            setResponse(bytes, response, fileName);
                        }
                    }

                    // 视频
                    String videoUrlBasePath = ftpAccountConfig.getVideoUrlBasePath();
                    if (filePath.contains(videoUrlBasePath)) {
                        String[] split = filePath.split(videoUrlBasePath);
                        if (split.length == 2) {
                            String videoPath = ftpAccountConfig.getVideoSaveBasePath() + "/" + split[1];
                            log.info("视频下载地址为:[{}]", videoPath);
                            byte[] bytes = FileUtil.getBytesByFile(videoPath);
                            setResponse(bytes, response, fileName);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("文件下载出现问题,原因:", e);
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        return serviceResult;
    }

    /**
     * 拼装返回信息
     *
     * @param bytes    文件内容
     * @param response 返回信息
     */
    private void setResponse(byte[] bytes, HttpServletResponse response, String fileName) throws IOException {
        if (bytes != null) {
            OutputStream os = response.getOutputStream();
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + bytes.length);
            os.write(bytes);
            os.flush();
            os.close();
        }
    }

    /**
     * 根据文件路径获取文件名称
     *
     * @param filePath 文件路径
     * @return 返回文件名称
     */
    private JSONObject getFilePathNameByFilePath(String filePath) {
        JSONObject json = new JSONObject();
        int i = filePath.lastIndexOf("/");
        if (i > 0) {
            String fileName = filePath.substring(i + 1);
            String path = filePath.substring(0, i);
            json.put(RepairOrderFilesConstant.FILE_NAME, fileName);
            json.put(RepairOrderFilesConstant.PATH, path);
        }
        return json;
    }
}